package com.example.AIstudy.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.example.AIstudy.domain.User;
import com.example.AIstudy.service.WechatService;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
public class WechatServiceImpl implements WechatService {
    private static final String APP_ID = "wx755a68b7f6fdda74";
    private static final String APP_SECRET = "91b2c7f68132ce05b067df0890c4d002";

    @Override
    public String codeToOpenId(String code) {
        // 构建请求URL
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        // 发送HTTP请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(url, String.class);
        // 处理响应，提取OpenID等信息
        JSONObject jsonObject = JSONObject.parseObject(response);
        String openid = jsonObject.getString("openid");
        return openid;
    }

    //根据accesstoken和openid获取到用户的信息，以字符串的形式返回
    public String getUserInfo(String accessToken, String openId) {

        String USER_INFO_url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId+"&lang=zh_CN";
        // 发送HTTP请求
        RestTemplate restTemplate = new RestTemplate();
        String response = restTemplate.getForObject(USER_INFO_url, String.class);
        //返回字符串
        return response;
    }

}
